package com.cloudeye.im.easemob;

import com.easemob.im.server.api.Context;
import com.easemob.im.server.api.group.create.CreateGroup;
import com.easemob.im.server.api.group.create.CreateGroupResponse;
import com.easemob.im.server.exception.EMUnknownException;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

/**
 * @Author: lafangyuan
 * @Date: 2021/11/1 11:20
 */
public class EaseMobGreateGroup extends CreateGroup {

    private Context context;

    public EaseMobGreateGroup(Context context) {
        super(context);
        this.context = context;
    }

    public Mono<String> group(EaseMobCreateGroupRequest groupRequest) {
        return this.context.getHttpClient().flatMap((httpClient) -> {
            return ((HttpClient.RequestSender)httpClient.post().uri("/chatgroups")).send(Mono.create((sink) -> {
                sink.success(this.context.getCodec().encode(groupRequest));
            })).responseSingle((rsp, buf) -> {
                this.context.getErrorMapper().statusCode(rsp);
                return buf;
            }).doOnNext((buf) -> {
                this.context.getErrorMapper().checkError(buf);
            });
        }).map((buf) -> {
            return (CreateGroupResponse)this.context.getCodec().decode(buf, CreateGroupResponse.class);
        }).handle((rsp, sink) -> {
            String groupId = rsp.getGroupId();
            if (groupId == null) {
                sink.error(new EMUnknownException("groupId is null"));
            }

            sink.next(groupId);
        });
    }
}
